package com.jp.knowledge.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiayen.cache.FileCacheManager;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.InfoDataDetailActivity;
import com.jp.knowledge.activity.JpApplicationWebActivity;
import com.jp.knowledge.activity.SearchActivity;
import com.jp.knowledge.activity.SearchSimpleActivity;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.adapter.SearchCommtemAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.command.Command;
import com.jp.knowledge.command.CommandInvoker;
import com.jp.knowledge.command.CommandReceiver;
import com.jp.knowledge.logic.SearchLogic;
import com.jp.knowledge.model.HeadLineData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.refresh.JpRefreshView;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jiayen on 16/10/27.
 * 关注详情
 */
public class SearchDetailFragment extends BaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, SearchLogic.SearchCallBack {

    private final int GET_DETAIL_LIST_CODE = 0x00000001;//获取详情列表

    @ViewInject(R.id.m_refresh)
    private CanRefreshLayout mRefresh;

    @ViewInject(R.id.can_content_view)
    protected RecyclerView recyclerView;

    @ViewInject(R.id.can_refresh_footer)
    protected JpRefreshView footerView;

    @ViewInject(R.id.no_search_content)
    private LinearLayout noSearchLayout;

    protected View mView;

    private SearchCommtemAdapter adpter;
    protected List<HeadLineData> list;

    private LocalBroadCast localBroadCast;
    private LocalBroadcastManager localBroadcastManager;

    protected String label;
    protected int type;
    protected int subType;
    protected String infoId;
    protected String action;
    protected String id;
    protected int webType;
    private  int aciontType;
    private int level;
    private String searchId;//搜索需要的大类id

    private FileCacheManager cacheManager;

    private SearchLogic searchLogic;
    private int pageNo = 1;

    protected boolean isFresh=true;//刷新
    private int sourceType=0;
    public SearchDetailFragment(){
        webType = -1;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(mView == null) {
            mView = inflater.inflate(R.layout.search_detail_fragment, null);
            x.view().inject(this, mView);
            initBroadCast();
            initData();
        }
        return mView;
    }

    private void initBroadCast(){
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if(LocalBroadCast.DETAIL_SC_BROAD.equals(action)) {
                    for (HeadLineData data : list) {
                        if (data.getId() != null && data.getId().equals(intent.getStringExtra("id"))) {
                            data.setIsFollow(intent.getIntExtra("isCollection", 0));
                            adpter.updataAdapter(list);
                            return;
                        }
                    }
                } else if(LocalBroadCast.COMM_CHANGE_SIZE.equals(action)){
                    adpter.changeTextSize();
                }
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.DETAIL_SC_BROAD);
        intentFilter.addAction(LocalBroadCast.COMM_CHANGE_SIZE);
        localBroadcastManager.registerReceiver(localBroadCast, intentFilter);
    }

    @Override
    public void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        super.onDestroy();
    }

    public void setAction(String action){
        this.action = action;
        if(adpter != null) {
            adpter.setAction(action);
        }
    }

    public void setId(String id){
        this.id = id;
        if(adpter != null) {
            adpter.setId(id);
        }
    }

    public void setWebType(int type){
        this.webType = type;
        if(adpter != null) {
            adpter.setType(type);
        }
    }

    public void setInfoId(String infoId) {
        this.infoId = infoId;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public void setType(int type) {
        this.type = type;
    }

    public void setAction(int action) {
        this.aciontType = action;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public void setSearchId(String searchId) {
        this.id = searchId;
    }

    public int getSubType() {
        return subType;
    }

    public void setSubType(int subType) {
        this.subType = subType;
    }

    protected void initData() {

        sourceType = getActivity().getIntent().getIntExtra("sourceType",0);
        if(sourceType==1){//代表是岗位知识详情过来的 隐藏tab

        }

        cacheManager = new FileCacheManager();
        mRefresh.setLoadMoreEnabled(true);
        mRefresh.setRefreshEnabled(true);
        mRefresh.setTag(false);

        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(manager);
        list = new ArrayList<>();
        adpter = new SearchCommtemAdapter(mContext, list);
        if(getActivity() instanceof SearchSimpleActivity)
            adpter.setShowLabel(false);
        adpter.setId(id);
        adpter.setAction(action);
        adpter.setType(webType);

        recyclerView.setAdapter(adpter);

        searchLogic = new SearchLogic(mContext);
        searchLogic.setSearchCallBack(this);
        mRefresh.autoRefresh();

        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);

        adpter.setOnItemListener(new OnItemListerner() {
            @Override
            public void onItemClick(View view, int i) {
                adpter.updateTitleColor(i);
                HeadLineData data = list.get(i);
                CommandReceiver commandReceiver = new CommandReceiver.Builder(mContext)
                        .withCompanyId(data.getCompanyId())
                        .withRecordId(data.getRecordId())
                        .withParameterId(data.getParameterId() + "")
                        .build();
                Command commandObject = Command.create(data.getCommand(), commandReceiver);
                CommandInvoker.executeCommand(commandObject);

//                Intent intent = new Intent(mContext, InfoDataDetailActivity.class);
//                intent.putExtra("id", list.get(i).getId());
//                intent.putExtra("type", list.get(i).getType());
//                intent.putExtra("linkTitle", list.get(i).getTitle());
//                try {
//                    intent.putExtra("linkIcon", list.get(i).getImglist().get(0).getSrc());
//                } catch (Exception e){} finally {
//                    startActivity(intent);
//                }

//                switch (type){
//                    case 3: // "公司";
//                        JpApplicationWebActivity.gotoWebActivity(getContext(),
//                                "details/companyDetails?id=" + list.get(i).getId() + "&type=" + list.get(i).getType());
//                        break;
//                    case 4: // "人物";
//                        JpApplicationWebActivity.gotoWebActivity(getContext(),
//                                "details/figureDetails?id=" + list.get(i).getId() + "&type=" + list.get(i).getType());
//                        break;
//                    case 8: // "产品";
//                        JpApplicationWebActivity.gotoWebActivity(getContext(),
//                                "details/productDetails?id=" + list.get(i).getId() + "&type=" + list.get(i).getType());
//                        break;
//                    case 11: // "全民推荐";
//                        JpApplicationWebActivity.gotoWebActivity(getContext(),
//                                "details/recommendDetail?id=" + list.get(i).getId() + "&type=" + list.get(i).getType());
//                        break;
//                    default:
//                        Intent intent = new Intent(mContext, InfoDataDetailActivity.class);
//                        intent.putExtra("id", list.get(i).getId());
//                        intent.putExtra("type", list.get(i).getType());
//                        intent.putExtra("linkTitle", list.get(i).getTitle());
//                        try {
//                            intent.putExtra("linkIcon", list.get(i).getImglist().get(0).getSrc());
//                        } catch (Exception e){} finally {
//                            startActivity(intent);
//                        }
//                        break;
//                }
            }
        });

        ((SearchActivity)mContext).setCallBack(new SearchActivity.Callback() {
            @Override
            public void done() {
                pageNo=1;
                search(pageNo);
            }
        });
    }

    /**
     * 执行搜索，供外部调用
     */
    public void doSearch(){
        if(noSearchLayout != null)
            noSearchLayout.setVisibility(View.GONE);
        clearList();
        if(mRefresh != null) {
            mRefresh.autoRefresh();
            footerView.setLoadComplete(false);
        }
    }

    /* 用于检测是否搜索失败，共外部调用 */
    public boolean checkIsSearchSuccess(){
        if(noSearchLayout != null && noSearchLayout.getVisibility() == View.GONE
                && (list == null || list.size() == 0) && !(boolean) mRefresh.getTag())
            return false;
        return true;
    }

    /**
     * 执行搜索
     *
     * @param pageNo
     */
    private void search(int pageNo) {
        String keyword = ((SearchActivity) mContext).getKeyWord();
        if(action == null || action.trim().length() == 0)
            action = "library";

            searchLogic.search(keyword, type, subType, pageNo, action, id,aciontType,level);
    }

    /**
     * 清空搜索结果
     */
    public void clearList(){
        if(list == null)
            return;
        list.clear();
        adpter.updataAdapter(list);
    }


    @Override
    public void onRefresh() {
        isFresh=true;
        mRefresh.setTag(true);
        pageNo=1;
        search(pageNo);
    }

    @Override
    public void onLoadMore() {
        mRefresh.setTag(true);
        isFresh = false;
        if(footerView.isLoadComplete())
            compelete();
        else
            search(++pageNo);
    }

    @Override
    public void done(IModel dataModel) {
        List<HeadLineData> data = dataModel.getList(HeadLineData.class);
        if(isFresh) {
            list = data;
            footerView.setLoadComplete(false);
        }else{
            if(list==null)
                list = new ArrayList<>();
            if(data == null || data.size() == 0)
                footerView.setLoadComplete(true);
            list.addAll(data);
        }
        adpter.updataAdapter(list);
        if (list == null || list.size() == 0) {
            noSearchLayout.setVisibility(View.VISIBLE);
        } else {
            noSearchLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void compelete() {
        mRefresh.setTag(false);
        if(isFresh){mRefresh.refreshComplete();}
        else{
            mRefresh.loadMoreComplete();
            isFresh=true;
        }
    }
}
